<template>
  <!-- 操作栏 -->
  <div class="header">
    <div class="header-title">
      <svg-icon name="dictionary"></svg-icon>
      {{ $t('menus.Dictionary') }}
    </div>
    <div>
      <el-input
        v-model="queryForm.name"
        :placeholder="$t('btn.placeholder')"
        clearable
        :size="$store.getters.size"
        :prefix-icon="Search"
        class="header-input"
      ></el-input>
      <el-button
        type="primary"
        plain
        :icon="Search"
        :size="$store.getters.size"
        @click="initDictionaryList"
        >{{ $t('btn.search') }}</el-button
      >
      <el-button
        type="primary"
        :icon="Plus"
        :size="$store.getters.size"
        @click="handleDictionary()"
        >{{ $t('btn.addDictionary') }}</el-button
      >
      <el-button
        type="success"
        :icon="Plus"
        :size="$store.getters.size"
        @click="handleDictionaryData()"
        >{{ $t('btn.addData') }}</el-button
      >
    </div>
  </div>
  <div class="dictionary-container">
    <div class="left">
      <div class="left-title">字典目录</div>
      <div class="left-tag" v-for="(item, index) in tableMenus" :key="item.id">
        <el-tag
          closable
          :size="$store.getters.size"
          :effect="item.id === dictionaryId ? `dark` : `plain`"
          @click="selectDictionary(item.id)"
          @close="delDictionary(item)"
          >{{ item.name }}</el-tag
        >
        <el-tag
          class="edit"
          :size="$store.getters.size"
          @click="handleDictionary(item)"
          ><el-icon><Edit /></el-icon
        ></el-tag>
      </div>
    </div>
    <div class="right">
      <el-table
        :data="tableData"
        stripe
        border
        :size="$store.getters.size"
        style="width: 100%"
      >
        <el-table-column align="center" type="index" width="50" />
        <el-table-column
          header-align="center"
          :width="item.width"
          :align="item.align"
          :prop="item.prop"
          :label="$t(`table.${item.label}`)"
          v-for="(item, index) in options"
          :key="index"
        >
          <template v-slot="{ row }" v-if="item.prop === 'action'">
            <el-button
              type="primary"
              :icon="Edit"
              circle
              :size="$store.getters.size"
              @click="handleDictionaryData(row)"
            />
            <el-button
              type="danger"
              :icon="Delete"
              circle
              :size="$store.getters.size"
              @click="delDictionaryData(row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryForm.page_num"
        :small="$store.getters.size === 'small' ? true : false"
        :page-size="queryForm.page_size"
        :page-sizes="pageSizes"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <!-- 添加字典目录 或 修改字典目录 -->
  <dictionary-dialog
    v-model="dictionaryVisible"
    :dictionaryTitle="dictionaryTitle"
    v-if="dictionaryVisible"
    @initDictionaryList="initDictionaryList"
    :dictionaryValue="dictionaryValue"
  />
  <!-- 添加字典数据 或 修改字典数据 -->
  <Dialog
    v-model="dialogVisible"
    :dialogTitle="dialogTitle"
    v-if="dialogVisible"
    @initDictionaryDataList="initDictionaryDataList"
    :dialogTableValue="dialogTableValue"
    :currentRow="currentRow"
  />
</template>
<script setup>
import { ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search, Refresh } from '@element-plus/icons-vue'
import DictionaryDialog from './components/dictionaryDialog.vue'
import Dialog from './components/dialog.vue'
import { options } from './options.js'
import {
  getDictionaryList,
  getDictionaryDataList,
  deleteDictionary,
  deleteDictionaryData
} from '@/api/dictionary.js'
import { isNull } from '@/utils/common.js'
import { useI18n } from 'vue-i18n'
const i18n = useI18n()

// 字典库目录数据
const tableMenus = ref([])
const dictionaryId = ref(null)

// 添加字典目录 或 修改字典目录
const dictionaryVisible = ref(false)
const dictionaryTitle = ref('')
const dictionaryValue = ref({})
// 表格数据
const tableData = ref([])
// 总数
const total = ref(0)
// 搜索参数
const queryForm = ref({
  name: '',
  dictionary_id: 1,
  page_num: 1,
  page_size: 10
})
// 分页参数
const pageSizes = ref([20, 30, 40, 50, 100]) // 每页显示个数选择器的选项设置
const background = ref(true) // 是否为分页按钮添加背景色

// 新增数据 或 删除数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogTableValue = ref({})
const currentRow = ref({})

// 加载字典库目录数据
const initDictionaryList = async () => {
  const res = await getDictionaryList({ page_num: 1, page_size: 10000 })
  if (res.data.length > 0) {
    tableMenus.value = JSON.parse(JSON.stringify(res.data))
    const id = res.data[0].id
    dictionaryId.value = id
    initDictionaryDataList(id)
  } else {
    tableMenus.value = []
  }
}
initDictionaryList()

// 加载字典库明细数据
const initDictionaryDataList = async (dictionary_id) => {
  dictionary_id && (queryForm.value.dictionary_id = dictionary_id)
  const res = await getDictionaryDataList(queryForm.value)
  tableData.value = JSON.parse(JSON.stringify(res.data))
  total.value = res.total
}

// 新增字典目录 或 编辑字典目录
const handleDictionary = (row) => {
  if (isNull(row)) {
    dictionaryTitle.value = i18n.t('dialog.addDictionary') //'新增字典目录'
    dictionaryValue.value = {}
  } else {
    dictionaryTitle.value = i18n.t('dialog.editDictionary') //'编辑字典目录'
    dictionaryValue.value = JSON.parse(JSON.stringify(row))
  }
  dictionaryVisible.value = true
}
// 新增字典目录数据 或 编辑字典目录数据
const handleDictionaryData = (row) => {
  if (isNull(row)) {
    dialogTitle.value = i18n.t('dialog.addData') //'新增字典数据'
    currentRow.value = tableMenus.value.find(
      (item) => item.id === dictionaryId.value
    )
    dialogTableValue.value = {}
  } else {
    dialogTitle.value = i18n.t('dialog.editData') //'编辑字典数据'
    currentRow.value = tableMenus.value.find(
      (item) => item.id === dictionaryId.value
    )
    dialogTableValue.value = JSON.parse(JSON.stringify(row))
  }
  dialogVisible.value = true
}

// 删除字典目录
const delDictionary = async (row) => {
  ElMessageBox.confirm(i18n.t('dialog.deleteData'), i18n.t('dialog.tip'), {
    confirmButtonText: i18n.t('dialog.OK'), // OK
    cancelButtonText: i18n.t('dialog.Cancel'), // Cancel
    type: 'warning'
  })
    .then(async () => {
      const res = await deleteDictionary(row.id)
      res.status === 0
        ? ElMessage.success(i18n.t('message.deleteSuccess'))
        : ElMessage.error(i18n.t('message.deleteFailed'))
      res.status === 0 && initDictionaryList()
    })
    .catch((err) => {
      ElMessage({
        type: 'info',
        message: i18n.t('message.deleteCancel')
      })
    })
}

// 删除字典数据
const delDictionaryData = async (row) => {
  ElMessageBox.confirm(i18n.t('dialog.deleteData'), i18n.t('dialog.tip'), {
    confirmButtonText: i18n.t('dialog.OK'), // OK
    cancelButtonText: i18n.t('dialog.Cancel'), // Cancel
    type: 'warning'
  })
    .then(async () => {
      const res = await deleteDictionaryData(row.id)
      res.status === 0
        ? ElMessage.success(i18n.t('message.deleteSuccess'))
        : ElMessage.error(i18n.t('message.deleteFailed'))
      res.status === 0 && initDictionaryDataList()
    })
    .catch((err) => {
      ElMessage({
        type: 'info',
        message: i18n.t('message.deleteCancel')
      })
    })
}

// 初始化每页显示数量
const initPageSizes = () => {
  pageSizes.value.unshift(queryForm.value.page_size)
}
initPageSizes()

// 修改每页显示数量
const handleSizeChange = (pageSize) => {
  queryForm.value.page_num = 1
  queryForm.value.page_size = pageSize
  initDictionaryDataList(dictionaryId.value)
}

// 修改页码
const handleCurrentChange = (pageNum) => {
  queryForm.value.page_num = pageNum
  initDictionaryDataList(dictionaryId.value)
}

// 选择字典目录
const selectDictionary = (id) => {
  dictionaryId.value = id
  initDictionaryDataList(id)
}
</script>

<style lang="scss" scoped>
@import './index.scss';
@import '@/styles/header.scss';
</style>

<style>
.el-tabs--right .el-tabs__content,
.el-tabs--left .el-tabs__content {
  height: 100%;
}
</style>
